import {
  editInitList,
  initInstructAddressEdit,
  saveInstructAddressEdit,
} from '@/services/api/api-instruct-address';
import { TeamOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance, ProFormText } from '@ant-design/pro-form';
import { Button, message, Space, Spin, Tag, Transfer, Tree, Input } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import type { TreeDataNode } from 'antd';
import './index.less'
const { Search } = Input;
import { DataNode } from 'antd/es/tree';
import { trimStr } from '@/utils/tool';
interface EditAddressProps {
  id: string | undefined;
  name: string;
  onSave: () => void;
}
const getParentKey = (key: React.Key, tree: TreeDataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};
const EditAddress: React.FC<EditAddressProps> = ({ id, name, onSave }) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>([]);
  const [dataLoaded, setDataLoaded] = useState(false);
  const [dataCheckTreeContact, setDataCheckTreeContactState] = useState<any>();
  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);


  /**
     * 已经添加的用户列表
     */
  const [targetKeys, setTargetKeyss] = useState<string[]>([]);
  const dataList: { key: React.Key; title: string }[] = [];
  const generateList1 = (data: TreeDataNode[]) => {
    for (let i = 0; i < data?.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList1(node.children);
      }
    }
  };
  generateList1(dataTreeAddress);
  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();

    if (data) {
      data.forEach((val: any, idx, array) => {
        treeData.push({
          title: val.name,
          key: val.id,
          marks: val.marks,
          children: readyTreeAddressData(val.children as Array<UserData.Organization>),
        });
      });
    }

    return treeData;
  }
  /**
   * 加载单位树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      const response = await initInstructAddressEdit();
      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
        setDataLoaded(true)
      }
    } catch (error) { }
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setInputValue(value)

  };

  const onSearch = (val) => {
    const e = trimStr(val)
    if (e === '') {
      setAutoExpandParent(false);
      setExpandedKeys([]);
    } else {
      const newExpandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(e) > -1) {
            return getParentKey(item.key, dataTreeAddress);
          }
          return null;
        })
        .filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
      setExpandedKeys(newExpandedKeys);
      setAutoExpandParent(true);
    }
    setSearchValue(e);
  }


  const treeData = useMemo(() => {
    const loop = (data: TreeDataNode[]): TreeDataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
              {item?.marks && item?.marks.length > 0 && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </span>
          ) : (
            <>
              <span>{strTitle}</span>
              {item?.marks && item?.marks.length > 0 && searchValue && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(dataTreeAddress);
  }, [dataTreeAddress, searchValue]);



  const getCheckedIds = async (id: string) => {
    const res = await editInitList({ id })
    if (res.code === 0) {
      setTargetKeyss(res.data),
        setDataCheckTreeContactState(res.data)
    }
  }

  return (
    <DrawerForm
      title={id === undefined ? '新增联络人' : <span>{name}</span>}
      key={''}
      trigger={
        id === undefined ? (
          <Button key="button" icon={<TeamOutlined />} type="primary">
            新增联络人
          </Button>
        ) : (
          <span>{name}</span>
        )
      }
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        // forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: '100%',
      }}
      onFinish={async (values) => {
        const response = await saveInstructAddressEdit({
          combineIds: targetKeys,
          id: id,
          ...values,
        });

        if (response.code === 0) {
          setTargetKeyss([]);
          message.success('添加成功');
          onSave();
          return true;
        }
      }}
      onVisibleChange={(visible) => {
        if (visible) {
          loadAddressTreeData()
          if (id) {
            getCheckedIds(id)
            formRef.current?.setFieldsValue({ name })
          }
        } else {
          setExpandedKeys([])
          setDataCheckTreeContactState([])
          setInputValue('')
        }
      }}
    >
      <ProFormText
        width="xl"
        name="name"
        label="联络人名称"
        placeholder="请输入联络人名称"
        rules={[{ required: true, message: '这是必填项' }]}
        fieldProps={{
          maxLength: 200,
          allowClear: true,
        }}
      />
      <Spin spinning={!dataLoaded}>
        <Search style={{ marginBottom: 8 }} placeholder="输入名称查询" onChange={onChange} value={inputValue} onSearch={onSearch} allowClear/>
        {/* {dataLoaded ? <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          checkedKeys={dataCheckTreeContact}
          treeData={treeData}
          checkable
          selectable={false}
          // treeData={dataTreeAddress}
          onCheck={(e, info) => {
            console.log(e);
            setTargetKeyss(e),
              setDataCheckTreeContactState(e)
          }}
        /> : <>加载数据中...</>} */}
        {id ? ((dataLoaded && dataCheckTreeContact) && <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          checkedKeys={dataCheckTreeContact}
          treeData={treeData}
          defaultExpandAll={true}
          checkable
          selectable={false}
          // treeData={dataTreeAddress}
          onCheck={(e, info) => {
            console.log(e);
            setTargetKeyss(e),
              setDataCheckTreeContactState(e)
          }}
        />) : dataLoaded ? <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          checkedKeys={dataCheckTreeContact}
          treeData={treeData}
          checkable
          selectable={false}
          // treeData={dataTreeAddress}
          onCheck={(e, info) => {
            console.log(e);
            setTargetKeyss(e),
              setDataCheckTreeContactState(e)
          }}
        /> : <>加载数据中...</>}
      </Spin>
    </DrawerForm>
  );
};

export default EditAddress;
